#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :jd_spider_purchase_price.py
# Time  :2025/4/8 10:27
# Email :fortunatedong@163.com
# Author:by Adonli
import os
import time

import streamlit as st
import pandas as pd
from config import ROOT_DIR
from utils.jingdong_spider.purchase_price import GetJingDongPurchase
from config import Header_space
Header_space()
jingdong_spider_purchase_sku_path = os.path.join(ROOT_DIR, 'Datas', 'jingdong_spider_purchase_sku.csv')
jingdong_spider_purchase_price_path = os.path.join(ROOT_DIR, 'Datas', 'jingdong_spider_purchase_price.csv')


if "start_spider" not in st.session_state:
    st.session_state.start_spider = False
st.subheader("批量采集京东采购价格", divider=True)
col1, col2, col3 = st.columns([3,2,5],border=True)

with col1:
    # with st.container(height=600,border=True):
    if os.path.exists(jingdong_spider_purchase_sku_path):
        try:
            df = pd.read_csv(jingdong_spider_purchase_sku_path, index_col=False, dtype=str, keep_default_na=False)
        except Exception as e:
            df = pd.DataFrame(
                [
                    {"商品编号": "",},
                ]
            )
            df.to_csv(jingdong_spider_purchase_sku_path, index=False)
        finally:
            df = pd.read_csv(jingdong_spider_purchase_sku_path, index_col=False, dtype=str, keep_default_na=False)
        # print(df)
    else:
        df = pd.DataFrame(
            [
                {"商品编号": ""},
            ]
        )
        df.to_csv(jingdong_spider_purchase_sku_path, index=False)
        df = pd.read_csv(jingdong_spider_purchase_sku_path, index_col=False, dtype=str, keep_default_na=False)
    config = {
        '商品编号': st.column_config.TextColumn(),
    }
    result = st.data_editor(df, column_config=config, num_rows='dynamic')
    col1_col1, col1_col2 = st.columns([2, 1])
    with col1_col2:
        if st.button('保存'):
            result.to_csv(jingdong_spider_purchase_sku_path, index=False)
            st.success("成功保存")
            time.sleep(1)
            st.rerun()
with col2:
    option = st.selectbox("选择查询账号：", ["jd_aqrAaxqwcjCq", "金穗隆集团"],
                 index=None,placeholder="选择账号...")

    if st.button('开始采集'):
        st.session_state.start_spider = True
        with st.spinner("Wait for it...", show_time=True):
            result = GetJingDongPurchase(option).save_sku_price_data_dataframe()
            if result["code"] == 0:
                st.success(result["message"])
            else:
                st.session_state.start_spider = False
                st.error(result["message"])
with col3:
    if st.session_state.start_spider:
        df = pd.read_csv(jingdong_spider_purchase_price_path,index_col=False, dtype=str, keep_default_na=False)
        config = {
            '商品编号': st.column_config.TextColumn(),
            '含税价': st.column_config.TextColumn(),
            '不含税价': st.column_config.TextColumn(),
            '税率': st.column_config.TextColumn(),
            '税额': st.column_config.TextColumn(),
        }
        st.dataframe(df, column_config=config,key="purhase_table")
